#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <cstdlib>
#include <ctime>
#include "Mutex.hpp"

using namespace MutexModule;

// 共享数据
int shared_data = 0;

// 读写锁
pthread_rwlock_t rwlock;


void* Reader(void* arg){
	int num = *(int*) arg;
	while(true){
		pthread_rwlock_rdlock(&rwlock);
		std::cout << "读者-" << num << "正在工作，读到的数据为：" << shared_data << std::endl;
		pthread_rwlock_unlock(&rwlock);
		sleep(1);
	}

	delete (int*) arg;
	return nullptr;
}

void* Writer(void* arg){
	int num = *(int*) arg;
	while(true){
		pthread_rwlock_wrlock(&rwlock);
		shared_data = rand() % 100;
		std::cout << "写者-" << num << "正在工作，写入的数据为：" << shared_data << std::endl;
		pthread_rwlock_unlock(&rwlock);
		sleep(1);
	}

	delete (int*) arg;
	return nullptr;
}

int main()
{
	srand(time(nullptr));
	pthread_rwlock_init(&rwlock, nullptr);

	pthread_t reader[3], writer[2];
	for(int i = 0; i < 3; i++){
		pthread_create(&reader[i], nullptr, Reader, &i);
		sleep(1);
	}

	
	for(int i = 0; i < 2; i++){
		pthread_create(&writer[i], nullptr, Writer, &i);
		sleep(1);
	}

	for(int i = 0; i < 3; i++){
		pthread_join(reader[i], nullptr);
	}

	for(int i = 0; i < 2; i++){
		pthread_join(writer[i], nullptr);
	}

	pthread_rwlock_destroy(&rwlock);

	return 0;
}
